#!/bin/sh
PID_FILE="get_ext_ip.pid"
IP_FILE="/Data/Public/curr_ip.txt"
IP_HIST="/Data/Public/ip_hist.txt"

if [ -f "$PID_FILE" ]; then
  pid=$( head "$PID_FILE" )
  if [ "X$pid" != "X" ]; then
    chk=$( ps | grep " $pid " |  grep "get_ext_ip.sh" | grep -v "grep" | wc -l )
	if [ $chk -ne 0 ]; then
	  echo "Process $pid already running"
	  exit
	fi
  fi
fi

cur=$( cut -d ' ' -f 4 /proc/self/stat )
echo $cur > "$PID_FILE"

if [ -f "$IP_FILE" ]; then
  cip=$( head "$IP_FILE" )
  if [ "X$cip" = "X" ]; then
    pip="ayhaga"
  else
    pip=$cip
  fi
else
  pip="ayhaga"
fi

cip=`curl -s http://ipecho.net/plain`
if [ "$cip" != "$pip" ] && [ "X$cip" != "X" ]; then
  echo $cip | grep -E '\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b' > "$IP_FILE"
  if [ "$pip" != "ayhaga" ]; then
    grep $pip "$IP_HIST" 2>/dev/null | wc -l
    oip=`grep $pip "$IP_HIST" 2>/dev/null | wc -l`
    if [ $oip = 0 ]; then
     echo $pip >> "$IP_HIST"
     sort -n "$IP_HIST" > "$IP_HIST"
    fi
  fi
fi
